package com.roger.homecenterscreen.utils

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

/**
 * MIUI系统权限管理器
 * 专门处理MIUI系统的权限问题和兼容性
 */
class MIUIPermissionManager(private val context: Context) {
    
    companion object {
        private const val TAG = "MIUIPermissionManager"
        private const val REQUEST_CODE_PERMISSIONS = 1001
        private const val REQUEST_CODE_SETTINGS = 1002
    }
    
    /**
     * 检查所有必要权限
     */
    fun checkAllPermissions(): Boolean {
        val requiredPermissions = getRequiredPermissions()
        return requiredPermissions.all { permission ->
            ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
        }
    }
    
    /**
     * 获取必要的权限列表
     */
    private fun getRequiredPermissions(): Array<String> {
        val permissions = mutableListOf<String>().apply {
            add(Manifest.permission.INTERNET)
            add(Manifest.permission.ACCESS_NETWORK_STATE)
            add(Manifest.permission.ACCESS_WIFI_STATE)
            add(Manifest.permission.ACCESS_FINE_LOCATION)
            add(Manifest.permission.ACCESS_COARSE_LOCATION)
            
            // 语音功能权限
            add(Manifest.permission.RECORD_AUDIO)
            // 最小化：仅保留录音 + 音频设置
            // 其他权限后续按需请求，避免一次性弹窗全部被拒
            add(Manifest.permission.MODIFY_AUDIO_SETTINGS)
            
            // 存储与电话相关权限暂不请求，避免影响首次体验
            
            // 位置与电话权限暂不加入首次请求
        }
        
        return permissions.toTypedArray()
    }
    
    /**
     * 请求所有必要权限
     */
    fun requestAllPermissions(activity: Activity) {
        try {
            Log.i(TAG, "开始请求所有必要权限")
            
            val requiredPermissions = getRequiredPermissions()
            val missingPermissions = requiredPermissions.filter { permission ->
                ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED
            }
            
            if (missingPermissions.isNotEmpty()) {
                Log.i(TAG, "缺少权限: ${missingPermissions.joinToString()}")
                ActivityCompat.requestPermissions(
                    activity,
                    missingPermissions.toTypedArray(),
                    REQUEST_CODE_PERMISSIONS
                )
            } else {
                Log.i(TAG, "所有权限已授予")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "请求权限失败", e)
        }
    }
    
    /**
     * 处理权限请求结果
     */
    fun handlePermissionResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
        activity: Activity
    ): Boolean {
        if (requestCode != REQUEST_CODE_PERMISSIONS) {
            return false
        }
        
        try {
            val grantedPermissions = mutableListOf<String>()
            val deniedPermissions = mutableListOf<String>()
            
            for (i in permissions.indices) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    grantedPermissions.add(permissions[i])
                } else {
                    deniedPermissions.add(permissions[i])
                }
            }
            
            Log.i(TAG, "权限请求结果 - 已授予: ${grantedPermissions.size}, 被拒绝: ${deniedPermissions.size}")
            
            if (deniedPermissions.isNotEmpty()) {
                // 过滤掉废弃的存储权限（Android 11+）
                val filteredDeniedPermissions = deniedPermissions.filter { permission ->
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        permission != Manifest.permission.WRITE_EXTERNAL_STORAGE &&
                        permission != Manifest.permission.READ_EXTERNAL_STORAGE
                    } else {
                        true
                    }
                }
                
                Log.w(TAG, "被拒绝的权限: ${deniedPermissions.joinToString()}")
                
                if (filteredDeniedPermissions.isNotEmpty()) {
                    Log.w(TAG, "需要关注的被拒绝权限: ${filteredDeniedPermissions.joinToString()}")
                    
                    // 检查是否为关键权限
                    val criticalPermissions = filteredDeniedPermissions.filter { permission ->
                        permission == Manifest.permission.RECORD_AUDIO ||
                        permission == Manifest.permission.ACCESS_FINE_LOCATION ||
                        permission == Manifest.permission.READ_PHONE_STATE
                    }
                    
                    if (criticalPermissions.isNotEmpty()) {
                        Log.w(TAG, "关键权限被拒绝，可能影响核心功能: ${criticalPermissions.joinToString()}")
                        
                        // 对于被拒绝的关键权限，检查是否需要显示说明
                        val shouldShowRationale = criticalPermissions.any { permission ->
                            ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
                        }
                        
                        if (!shouldShowRationale && SystemUtils.isMIUI()) {
                            // MIUI系统，可能需要手动设置
                            Log.i(TAG, "MIUI系统检测到关键权限被永久拒绝，引导用户手动设置")
                            showMIUIPermissionGuide(activity)
                        }
                        return false
                    } else {
                        Log.i(TAG, "被拒绝的权限都是非关键权限，应用可以继续运行")
                        return true
                    }
                } else {
                    Log.i(TAG, "被拒绝的权限都是非必需的（如废弃的存储权限），应用可以正常运行")
                    return true
                }
            }
            
            return true
            
        } catch (e: Exception) {
            Log.e(TAG, "处理权限结果失败", e)
            return false
        }
    }
    
    /**
     * 显示MIUI权限设置指南
     */
    private fun showMIUIPermissionGuide(activity: Activity) {
        try {
            Log.i(TAG, "显示MIUI权限设置指南")
            
            // 尝试直接打开应用权限设置页面
            val intent = Intent().apply {
                action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                data = Uri.fromParts("package", context.packageName, null)
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
            
            if (intent.resolveActivity(context.packageManager) != null) {
                context.startActivity(intent)
                Log.i(TAG, "已打开应用权限设置页面")
            } else {
                // 如果无法打开，则打开通用设置页面
                val fallbackIntent = Intent(Settings.ACTION_SETTINGS)
                context.startActivity(fallbackIntent)
                Log.i(TAG, "已打开通用设置页面")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "打开权限设置页面失败", e)
        }
    }
    
    /**
     * 检查网络权限状态
     */
    fun checkNetworkPermissions(): Boolean {
        return try {
            val internetPermission = ContextCompat.checkSelfPermission(
                context, 
                Manifest.permission.INTERNET
            ) == PackageManager.PERMISSION_GRANTED
            
            val networkStatePermission = ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_NETWORK_STATE
            ) == PackageManager.PERMISSION_GRANTED
            
            Log.d(TAG, "网络权限状态 - INTERNET: $internetPermission, NETWORK_STATE: $networkStatePermission")
            
            internetPermission && networkStatePermission
            
        } catch (e: Exception) {
            Log.e(TAG, "检查网络权限失败", e)
            false
        }
    }
    
    /**
     * 检查位置权限状态
     */
    fun checkLocationPermissions(): Boolean {
        return try {
            val fineLocationPermission = ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
            
            val coarseLocationPermission = ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
            
            Log.d(TAG, "位置权限状态 - FINE: $fineLocationPermission, COARSE: $coarseLocationPermission")
            
            fineLocationPermission || coarseLocationPermission
            
        } catch (e: Exception) {
            Log.e(TAG, "检查位置权限失败", e)
            false
        }
    }
    
    /**
     * 检查语音权限状态
     */
    fun checkVoicePermissions(): Boolean {
        return try {
            val recordAudioPermission = ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.RECORD_AUDIO
            ) == PackageManager.PERMISSION_GRANTED
            
            val phoneStatePermission = ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.READ_PHONE_STATE
            ) == PackageManager.PERMISSION_GRANTED
            
            val audioSettingsPermission = ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.MODIFY_AUDIO_SETTINGS
            ) == PackageManager.PERMISSION_GRANTED
            
            Log.d(TAG, "语音权限状态 - RECORD_AUDIO: $recordAudioPermission, READ_PHONE_STATE: $phoneStatePermission, MODIFY_AUDIO_SETTINGS: $audioSettingsPermission")
            
            recordAudioPermission && phoneStatePermission && audioSettingsPermission
            
        } catch (e: Exception) {
            Log.e(TAG, "检查语音权限失败", e)
            false
        }
    }
    
    /**
     * 处理MIUI特有的权限问题
     */
    fun handleMIUISpecificIssues() {
        if (!SystemUtils.isMIUI()) {
            return
        }
        
        try {
            Log.i(TAG, "处理MIUI特有权限问题")
            
            // 检查自启动权限
            checkAutoStartPermission()
            
            // 检查电池优化
            checkBatteryOptimization()
            
            // 检查网络权限
            if (!checkNetworkPermissions()) {
                Log.w(TAG, "网络权限可能受限，这可能导致RTMode权限错误")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "处理MIUI特有权限问题失败", e)
        }
    }
    
    /**
     * 检查自启动权限
     */
    private fun checkAutoStartPermission() {
        try {
            Log.d(TAG, "检查自启动权限")
            // 这里可以添加检查自启动权限的逻辑
            // 由于MIUI的限制，我们主要记录状态用于调试
        } catch (e: Exception) {
            Log.e(TAG, "检查自启动权限失败", e)
        }
    }
    
    /**
     * 检查电池优化
     */
    private fun checkBatteryOptimization() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val powerManager = context.getSystemService(Context.POWER_SERVICE) as android.os.PowerManager
                val isIgnoringBatteryOptimizations = powerManager.isIgnoringBatteryOptimizations(context.packageName)
                
                Log.d(TAG, "电池优化状态: 是否被忽略: $isIgnoringBatteryOptimizations")
                
                if (!isIgnoringBatteryOptimizations) {
                    Log.i(TAG, "应用可能受到电池优化限制")
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "检查电池优化失败", e)
        }
    }
    
    /**
     * 获取权限状态报告
     */
    fun getPermissionStatusReport(): String {
        return try {
            StringBuilder().apply {
                append("=== 权限状态报告 ===\n")
                append("系统: ${if (SystemUtils.isMIUI()) "MIUI ${SystemUtils.getMIUIVersion()}" else "标准Android"}\n")
                append("Android版本: ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})\n")
                append("包名: ${context.packageName}\n")
                append("\n权限状态:\n")
                
                getRequiredPermissions().forEach { permission ->
                    val isGranted = ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
                    append("  $permission: ${if (isGranted) "✅ 已授予" else "❌ 未授予"}\n")
                }
                
                append("\n功能状态:\n")
                append("  网络权限: ${if (checkNetworkPermissions()) "✅ 正常" else "❌ 受限"}\n")
                append("  位置权限: ${if (checkLocationPermissions()) "✅ 正常" else "❌ 受限"}\n")
                append("  语音权限: ${if (checkVoicePermissions()) "✅ 正常" else "❌ 受限"}\n")
                append("  所有权限: ${if (checkAllPermissions()) "✅ 全部授予" else "❌ 部分缺失"}\n")
                
            }.toString()
        } catch (e: Exception) {
            "获取权限状态报告失败: ${e.message}"
        }
    }
} 